﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using DHAA.Areas.Administrator.Models;
using DHAA.Global;

namespace DHAA.Areas.Administrator.Controllers
{
    public class CategoryController : Controller
    {
        private SqlConnection sqlConnection;
        readonly GlobalController globalController = new GlobalController();
        private SqlCommand sqlCommand;
        private SqlDataAdapter sqlDataAdapter;
      //  private DataSet dataSet;
        private CategoryModels catModel;
        private int count;


        public List<CategoryModels> SelectALLCat()
        {
            sqlConnection = globalController.getConnection();
            sqlDataAdapter = new SqlDataAdapter("SELECT CategoryID, CategoryName, ParentID, Image, Description FROM dbo.Categories", sqlConnection);
            DataSet ds = new DataSet();
            sqlDataAdapter.Fill(ds);
            DataTable dt = ds.Tables[0];
          
            
         
            var catalist = new List<CategoryModels>();
            
           
            foreach (DataRow r in dt.Rows)
            {
                catModel = new CategoryModels
                               {
                                   CategoryID = r.Field<int>("CategoryID"),
                                   CategoryName = r.Field<string>("CategoryName"),
                                   ParentID = r.Field<int>("ParentID"),
                                   Image = r.Field<string>("Image"),
                                   Description = r.Field<string>("Description")
                               };
                    catalist.Add(catModel);
            }
            return catalist;
        }


        public List<CategoryModels> SelectCategoryByParentID(int id)
        {
            sqlConnection = globalController.getConnection();
            sqlDataAdapter = new SqlDataAdapter("SelectCategoryByParentID", sqlConnection) { SelectCommand = { CommandType = CommandType.StoredProcedure } };
            SqlParameter pr = new SqlParameter("@ParentID", id);
            sqlDataAdapter.SelectCommand.Parameters.Add(pr);
            DataSet ds = new DataSet();
            sqlDataAdapter.Fill(ds);
            DataTable dt = ds.Tables[0];



            var catalist = new List<CategoryModels>();


            foreach (DataRow r in dt.Rows)
            {
                catModel = new CategoryModels
                {
                    CategoryID = r.Field<int>("CategoryID"),
                    CategoryName = r.Field<string>("CategoryName"),
                    ParentID = r.Field<int>("ParentID"),
                    Image = r.Field<string>("Image"),
                    Description = r.Field<string>("Description"),
                    ParentName = r.Field<string>("ParentName"),
                    ChildCount = (int)new SqlCommand("Select Count(*) from categories where ParentID=" + r.Field<int>("CategoryID"), sqlConnection).ExecuteScalar(),
                    ProductCount = (int)new SqlCommand("Select Count(*) from products where CategoryID=" + r.Field<int>("CategoryID"), sqlConnection).ExecuteScalar()
                };
                catalist.Add(catModel);
            }
            return catalist;
        }

        public List<CategoryModels> SelectCategoryByID(int id)
        {

            sqlConnection = globalController.getConnection();
            sqlDataAdapter = new SqlDataAdapter("SelectCategoryByID", sqlConnection)
                                 {SelectCommand = {CommandType = CommandType.StoredProcedure}};
            SqlParameter pr = new SqlParameter("@CategoryID", id);
            sqlDataAdapter.SelectCommand.Parameters.Add(pr);
            DataSet ds = new DataSet("CateogoryByID");
            sqlDataAdapter.Fill(ds);

            DataTable catTable = ds.Tables[0];

            List<CategoryModels> resultList = new List<CategoryModels>();
            foreach (DataRow row in catTable.Rows )
            {
                catModel = new CategoryModels
                               {
                                   CategoryID = row.Field<int>("CategoryID"),
                                   CategoryName = row.Field<string>("CategoryName"),
                                   Description = row.Field<string>("Description"),
                                   Image = row.Field<string>("Image"),
                                   ParentID = row.Field<int>("ParentID"),
                                   ParentName = (string)new SqlCommand("Select CategoryName from categories where CategoryID=" + row.Field<int>("ParentID"), sqlConnection).ExecuteScalar(),
                                   ChildCount =(int) new SqlCommand("Select Count(*) from categories where ParentID=" +row.Field<int>("CategoryID"), sqlConnection).ExecuteScalar(),
                                   ProductCount = (int) new SqlCommand("Select Count(*) from products where CategoryID=" +row.Field<int>("CategoryID"), sqlConnection).ExecuteScalar()
                               };
                resultList.Add(catModel);

            }

            return resultList;

        }






        public ActionResult Index()
        {
            ViewData["menu"] = getMenu();
            return View();
        }


        public string getMenu()
        {
            var a = SelectALLCat();
            var menu = globalController.ListToTree(a, 0);
            return menu;

        }


        public ActionResult List(int parentID)
        {

            List<CategoryModels> catalist = SelectCategoryByParentID(parentID);

            ViewData["ParentID"] = parentID;
            return PartialView(catalist);
        }

        //
        // GET: /Administrator/Category/Details/5

        //
        // GET: /Administrator/Category/Create

        public ActionResult Create(int parentID)
        {
            List<CategoryModels> allcatalist = SelectALLCat();
            List<CategoryModels> catalist = allcatalist.Select(c => c).Where(c => c.CategoryID == parentID).ToList();
            CategoryModels cat;
            if(parentID == 0)
            {
                 cat = new CategoryModels{ParentID = 0, ParentName = "Root"};
            }
            else
            {
                cat = new CategoryModels
                                     {
                                         ParentID = catalist.Select(c => c.CategoryID).First(),
                                         ParentName = catalist.Select(c => c.CategoryName).First()
                                     };
            }
            
            
                                       

                
            return View(cat);
        } 

        //
        // POST: /Administrator/Category/Create

        [HttpPost]
        public ActionResult Upload(string qqfile)
        {
            var path = AppDomain.CurrentDomain.BaseDirectory + "Default/Imagesproduct/";
            var file = string.Empty;
           try
            {
                var stream = Request.InputStream;
                if (String.IsNullOrEmpty(Request["qqfile"]))
                {
                    // IE
                    HttpPostedFileBase postedFile = Request.Files[0];
                    stream = postedFile.InputStream;
                    file = Path.Combine(path, System.IO.Path.GetFileName(Request.Files[0].FileName));
                }
                else
                {
                    //Webkit, Mozilla
                    file = Path.Combine(path, qqfile);
                }

                var buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                System.IO.File.WriteAllBytes(file, buffer);
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message }, "application/json");
            }

            return Json(new { success = true }, "text/html");
        }



       
        [HttpPost]
        public ActionResult Create(CategoryModels model, FormCollection form)
        {
          
           try
           {
                sqlConnection = globalController.getConnection();
                sqlCommand = new SqlCommand("CreateNewCategory", sqlConnection){ CommandType = CommandType.StoredProcedure };
                var pr = new[]
                                      {
                                          new SqlParameter("@CategoryName", model.CategoryName), 
                                          new SqlParameter("@ParentID", model.ParentID), 
                                          new SqlParameter("@Image", model.Image), 
                                          new SqlParameter("@Description", model.Description), 
                                      };
                sqlCommand.Parameters.AddRange(pr);
                sqlCommand.ExecuteNonQuery();
                ViewData["MessageSuccess"] = "Create successfull";
                return View(model);
            }
            catch(SqlException se)
            {
                ViewData["MessageError"] = se.Message;
                return View();
            }
        }
        
        //
        // GET: /Administrator/Category/Edit/5
 
        public ActionResult Edit(int id)
        {
            CategoryModels category = SelectCategoryByID(id).First();
            return View(category);
        }

        //
        // POST: /Administrator/Category/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, CategoryModels model)
        {
            try
            {
                sqlConnection = globalController.getConnection();
                sqlCommand = new SqlCommand("UpdateCategory", sqlConnection) { CommandType = CommandType.StoredProcedure };
                var pr = new[]
                                      {
                                          new SqlParameter("@CategoryName", model.CategoryName), 
                                          new SqlParameter("@ParentID", model.ParentID), 
                                          new SqlParameter("@Image", model.Image), 
                                          new SqlParameter("@Description", model.Description),
                                          new SqlParameter("@CategoryID", id)
                                      };
                sqlCommand.Parameters.AddRange(pr);
                sqlCommand.ExecuteNonQuery();
                ViewData["MessageSuccess"] = "Update category successful";
                return View(model);
            }
            catch (SqlException se)
            {
                ViewData["MessageError"] = se.Message;
                return View();
            }
        }

        //
        // GET: /Administrator/Category/Delete/5
 
        public ActionResult Delete(int id)
        {
            CategoryModels model = SelectCategoryByID(id).First();

            return View(model);
        }

        //
        // POST: /Administrator/Category/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, CategoryModels model)
        {
            try
            {
                if(model.ChildCount > 0)
                {
                    ViewData["MessageError"] = "You can not delete this category because it has childrent categories";
                    return View(model); 
                }
                if (model.ProductCount > 0)
                {
                    ViewData["MessageError"] = "You can not delete this category because it contains products";
                    return View(model);
                }


                sqlConnection = globalController.getConnection();
                sqlCommand = new SqlCommand("DeleteCategory", sqlConnection) { CommandType = CommandType.StoredProcedure };
                var pr = new[]
                                      {
                                        new SqlParameter("@CategoryID", id)
                                      };
                sqlCommand.Parameters.AddRange(pr);
                sqlCommand.ExecuteNonQuery();
                ViewData["MessageSuccess"] = "Deleted successful";
                return PartialView("Message");
            }
            catch (SqlException se)
            {
                ViewData["MessageError"] = se.Message;
                return View();
            }
        }
    }
}
